package com.example.security.handle;

import com.example.security.bean.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/5/29 20:02
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    private SpringSessionBackedSessionRegistry sessionRegistry;

    public MyLogoutSuccessHandler(SpringSessionBackedSessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    private static final Logger log = LoggerFactory.getLogger(MyLogoutSuccessHandler.class);

    @Override
    public void onLogoutSuccess(HttpServletRequest request,HttpServletResponse res,Authentication authentication) throws IOException, ServletException {

        ResponseMsg.response(res,map -> {
            map.put("code",HttpStatus.OK.value());
            map.put("msg","注销登录成功");
            if (authentication != null) {
                UserInfo userInfo = (UserInfo) authentication.getPrincipal();
                List<SessionInformation> informations = sessionRegistry.getAllSessions(userInfo,true);
                informations.forEach(SessionInformation::expireNow);


                log.info("用户登出:{}",userInfo);
            }
        });

    }
}
